<?php

namespace app\admin\controller;

use app\common\controller\Backend;



use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 字体管理
 *
 * @icon fa fa-font
 */
class Font extends Backend
{
    
    /**
     * Font模型对象
     * @var \app\admin\model\Font
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Font;

    }

 



    /**
     * 导入
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        // $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        // foreach ($list as $k => $v) {
        //     if ($importHeadType == 'comment') {
        //         $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
        //     } else {
        //         $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
        //     }
        // }

        //加载文件
        $insert = [];

         //diy  
         $arr = [];
         //
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            // halt($PHPExcel);
            // bject(PhpOffice\PhpSpreadsheet\Spreadsheet)#28 (24) {
            //     ["uniqueID":"PhpOffice\PhpSpreadsheet\Spreadsheet":private] => string(23) "612726283c0771.59651904"
            //     ["properties":"PhpOffice\PhpSpreadsheet\Spreadsheet":private] => object(PhpOffice\PhpSpreadsheet\Document\Properties)#45 (12) {
            //       ["creator":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(5) "apple"
            //       ["lastModifiedBy":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(0) ""
            //       ["created":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => int(1571439900)
            //       ["modified":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => int(1629978594)
            //       ["title":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(0) ""
            //       ["description":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(0) ""
            //       ["subject":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(0) ""
            //       ["keywords":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(0) ""
            //       ["category":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(0) ""
            //       ["manager":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(0) ""
            //       ["company":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => string(21) "Microsoft Corporation"
            //       ["customProperties":"PhpOffice\PhpSpreadsheet\Document\Properties":private] => array(1) {
            //         ["KSOProductBuildVer"] => array(2) {
            //           ["value"] => string(15) "2052-3.8.1.6116"
            //           ["type"] => string(1) "s"
            //         }
            //       }
            //     }
            //     ["security":"PhpOffice\PhpSpreadsheet\Spreadsheet":private] => object(PhpOffice\PhpSpreadsheet\Document\Security)#46 (5) {
            //       ["lockRevision":"PhpOffice\PhpSpreadsheet\Document\Security":private] => bool(false)
            //       ["lockStructure":"PhpOffice\PhpSpreadsheet\Document\Security":private] => bool(false)
            //       ["lockWindows":"PhpOffice\PhpSpreadsheet\Document\Security":private] => bool(false)
            //       ["revisionsPassword":"PhpOffice\PhpSpreadsheet\Document\Security":private] => string(0) ""
            //       ["workbookPassword":"PhpOffice\PhpSpreadsheet\Document\Security":private] => string(0) ""
            //     }
            //     ["workSheetCollection":"PhpOffice\PhpSpreadsheet\Spreadsheet":private] => array(1) {
            //       [0] => object(PhpOffice\PhpSpreadsheet\Worksheet\Worksheet)#1641 (41) {
            //         ["parent":"PhpOffice\PhpSpreadsheet\Worksheet\Worksheet":private] => *RECURSION*
            //         ["cellCollection":"PhpOffice\PhpSpreadsheet\Worksheet\Worksheet":private] => object(PhpOffice\PhpSpreadsheet\Collection\Cells)#1630 (7) {
            //           ["cache":"PhpOffice\PhpSpreadsheet\Collection\Cells":private] => object(PhpOffice\PhpSpreadsheet\Collection\Memory)#34 (1) {
            //             ["cache":"PhpOffice\PhpSpreadsheet\Collection\Memory":private] => array(2475) {
            //               ["phpspreadsheet.6127262847e745.92439027.A1"] => object(PhpOffice\PhpSpreadsheet\Cell\Cell)#17980 (6) {
            //                 ["value":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => string(7) "第1盘"
            //                 ["calculatedValue":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //                 ["dataType":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => string(1) "s"
            //                 ["parent":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //                 ["xfIndex":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => int(2)
            //                 ["formulaAttributes":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //               }
            //               ["phpspreadsheet.6127262847e745.92439027.B1"] => object(PhpOffice\PhpSpreadsheet\Cell\Cell)#17979 (6) {
            //                 ["value":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => string(3) "阿"
            //                 ["calculatedValue":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //                 ["dataType":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => string(1) "s"
            //                 ["parent":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //                 ["xfIndex":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => int(3)
            //                 ["formulaAttributes":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //               }
            //               ["phpspreadsheet.6127262847e745.92439027.C1"] => object(PhpOffice\PhpSpreadsheet\Cell\Cell)#17981 (6) {
            //                 ["value":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => string(3) "啊"
            //                 ["calculatedValue":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //                 ["dataType":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => string(1) "s"
            //                 ["parent":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //                 ["xfIndex":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => int(4)
            //                 ["formulaAttributes":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //               }
            //               ["phpspreadsheet.6127262847e745.92439027.D1"] => object(PhpOffice\PhpSpreadsheet\Cell\Cell)#17982 (6) {
            //                 ["value":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => string(3) "艾"
            //                 ["calculatedValue":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //                 ["dataType":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => string(1) "s"
            //                 ["parent":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //                 ["xfIndex":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => int(4)
            //                 ["formulaAttributes":"PhpOffice\PhpSpreadsheet\Cell\Cell":private] => NULL
            //               }





            // http://font.he4966.cn/h.php/font/import?file=/uploads/20210826/3b5e0d7d9b6e16821995b7037f93a878.xlsx


            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
           
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号Aj 
            // halt($allColumn);//Aj
            // halt($currentSheet);
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行 69
            // halt($allRow);//69
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);//Aj 
            // halt($maxColumnNumber);//36
            // halt();
            $fields = [];
            // for ($currentRow = 1; $currentRow <= 1; $currentRow++) { //
            //     for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
            //         $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
            //         // dump($val);
            //         // </pre><pre>NULL
            //         // </pre><pre>string(3) "暗"
            //         // </pre><pre>NULL
            //         // </pre><pre>string(3) "昂"
            //         // </pre><pre>NULL
            //         // </pre><pre>string(3) "翱"
            //         // </pre><pre>NULL
            //         // </pre><pre>string(3) "鳌"
            //         // </pre><pre>NULL
             
            //         $fields[] = $val;
            //     }
            // }

            //Row  69行
                //                                          列，行
            $diy_val = $currentSheet->getCellByColumnAndRow(36, 6)->getValue();
            $diy_val = $currentSheet->getCellByColumnAndRow(1, 8)->getValue();
            halt($diy_val);
            for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) { //列Aj 36
                    // var_dump('hang:'.$currentRow,$currentColumn,$val);
                    if(!empty($val)){
                        $arr[$currentRow][] = $val; 
                    }
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();//获取某个单元的值
                    var_dump($currentColumn, $currentRow,$val);
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        halt($arr);
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['p'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('p')->visible(['p_name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

}
